﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using Microsoft.Crm.Sdk;
using TransactionServer.General_Classes;
using TS = TransactionServer.General_Classes;
using System.ComponentModel;
using Microsoft.VisualBasic.Activities;

namespace TransactionServer.CRM4Activities
{

    [Designer(typeof(TransactionServer.ActivityDesign.CRMActivities.CRMCreate))]
    public sealed class CRM4Create : CodeActivity
    {

        // Define an activity input argument of type string
        [RequiredArgument]
        public InArgument<TS.Context> Context { get; set; }
        [RequiredArgument]
        public InOutArgument<TS.Entity> Entity { get; set; }

        public CRM4Create()
        {
            VisualBasicValue<Context> vbArgument = new VisualBasicValue<Context>(Constants.CONTEXT_NAME);
            this.Context = InArgument<Context>.FromExpression(vbArgument);
        }

        // If your activity returns a value, derive from CodeActivity<TResult>
        // and return the value from the Execute method.
        protected override void Execute(CodeActivityContext context)
        {
            // Obtain the runtime value of the Text input argument
            TS.Entity Entity = context.GetValue(this.Entity);
            TS.Context con = context.GetValue(this.Context);
            CRM4Connector conn = (CRM4Connector)con.Connector[Entity.System];

            DynamicEntity crmEntity = conn.ConvertFrom(Entity);


            Guid id = conn.crmService.Create(crmEntity);

            Entity.Id = id.ToString();

            context.SetValue(this.Entity, Entity);
        }
    }
}
